package com.gin.no_gay_alliance.fragment.post;

import android.content.DialogInterface;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.EditText;

import androidx.appcompat.app.AlertDialog;

import com.gin.no_gay_alliance.customview.ColorSelectorWebView;
import com.gin.no_gay_alliance.databinding.DialogAddLinkBinding;
import com.gin.no_gay_alliance.databinding.DialogCollapseBinding;
import com.gin.no_gay_alliance.databinding.DialogDiceBinding;
import com.gin.no_gay_alliance.databinding.FragmentBbsCodeBinding;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.ClipboardUtils;
import com.gin.no_gay_alliance.utils.HandlerMessage;
import com.gin.no_gay_alliance.utils.InputMethodManagerUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.InsertText;
import com.gin.no_gay_alliance.viewmodel.InsertTextCollapse;
import com.gin.no_gay_alliance.viewmodel.InsertTextUrl;

import java.util.Locale;

/**
 * 发帖界面,添加bbsCode
 */
public class BbsCodeFragment extends BaseBindingFragment<FragmentBbsCodeBinding> implements View.OnClickListener {
    public static final String TAG = BbsCodeFragment.class.getSimpleName();
    private AlertDialog colorSelector;
    private ColorSelectorWebView colorSelectorWebView;

    @Override
    protected void onCreateView() {
        ViewUtils.setOnClickListener(this, b.tvBbsCodeTextColor, b.tvBbsCodeTextSize, b.tvBbsCodeQuote, b.tvBbsCodeCollapse, b.tvBbsCodeLink, b.tvBbsCodeDeleteLine, b.tvBbsCodeBold, b.tvBbsCodeUnderLined, b.tvBbsCodeItalic, b.tvBbsCodeHeader, b.tvBbsCodeList, b.tvBbsCodeDice);


    }


    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        // 以下需要弹窗确认

        // 字体颜色
        if (v == b.tvBbsCodeTextColor) {
            if (colorSelectorWebView == null) {
                colorSelectorWebView = new ColorSelectorWebView(requireActivity(), handler);
                colorSelectorWebView.addJavascriptInterface(this, "android");
            }

            colorSelector = AlertDialogUtils.showConfirm(requireContext(), "字体颜色", "可以先选中文字再设置颜色", colorSelectorWebView, null);
            colorSelector.setOnDismissListener(dialog -> {
                if (colorSelectorWebView.getParent() != null) {
                    ((ViewGroup) colorSelectorWebView.getParent()).removeView(colorSelectorWebView);
                }
            });
        }
        // 折叠框
        if (v == b.tvBbsCodeCollapse) {
            DialogCollapseBinding b = DialogCollapseBinding.inflate(getLayoutInflater());

            AlertDialogUtils.showConfirm(requireContext(), "添加折叠框", null, b.getRoot(), (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    String title = b.etTitle.getText().toString();
                    String content = b.etContent.getText().toString();
                    getParentHandler().sendMessage(getParentHandler().obtainMessage(HandlerMessage.INSERT_TEXT_COLLAPSE, new InsertTextCollapse(title, content)));
                }
            });

            b.etTitle.requestFocus();
            InputMethodManagerUtils.show(getParentHandler(), b.etTitle);
        }
        // 骰子
        if (v == b.tvBbsCodeDice) {
            DialogDiceBinding b = DialogDiceBinding.inflate(getLayoutInflater());

            AlertDialogUtils.showConfirm(requireContext(), "添加随机骰子", null, b.getRoot(), (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    String s = b.etRange.getText().toString();
                    String t = b.etCount.getText().toString();
                    if ("".equals(s)) {
                        toast("随机范围不能为空");
                        return;
                    }
                    int range = Integer.parseInt(s);
                    if (range <= 1) {
                        toast("随机范围必须大于1");
                        return;
                    }
                    int count = "".equals(t) ? 1 : Integer.parseInt(t);
                    if (count <= 0) {
                        toast("骰子数量必须大于0");
                        return;
                    }

                    String text = String.format(Locale.CHINA, "[dice]%dd%d[/dice]", count, range);
                    sendInsertMessage(text, null);
                }
            });
        }
        // 链接
        if (v == b.tvBbsCodeLink) {
            DialogAddLinkBinding b = DialogAddLinkBinding.inflate(getLayoutInflater());

            AlertDialogUtils.showConfirm(requireContext(), "插入链接", null, b.getRoot(), (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    String url = b.etUrl.getText().toString();
                    String title = b.etTitle.getText().toString();
                    if ("".equals(url)) {
                        getParentHandler().toast("链接地址不能为空");
                        return;
                    }
                    getParentHandler().sendMessage(getParentHandler().obtainMessage(HandlerMessage.INSERT_TEXT_URL, new InsertTextUrl(url, title)));
                }
            });

            // 检查剪贴板,如果是链接,直接填入链接栏
            String text = ClipboardUtils.getText(0);
            if (text != null && text.startsWith("http")) {
                b.etUrl.setText(text.replace("http:", "https:"));
                b.etTitle.requestFocus();
                InputMethodManagerUtils.show(getParentHandler(), b.etTitle);
            } else {
                // 没有链接 ,设置焦点到链接框
                b.etUrl.requestFocus();
                InputMethodManagerUtils.show(getParentHandler(), b.etUrl);
            }
        }
        //  字体大小
        if (v == b.tvBbsCodeTextSize) {
            EditText et = new EditText(requireActivity());
            et.setInputType(InputType.TYPE_CLASS_NUMBER);
            et.setText("100");

            AlertDialogUtils.showConfirm(requireContext(), "字体大小", "请输出大小百分比", et, (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    int per = Integer.parseInt(et.getText().toString());
                    String start = String.format(Locale.CHINA, "[size=%d%s]", per, "%");
                    sendInsertMessage(start, "[/size]");
                }
            });

            et.requestFocus();
            et.setSelection(0, et.getText().length());
            InputMethodManagerUtils.show(getParentHandler(), et);
        }

        // 以下直接插入

        //引用框
        if (v == b.tvBbsCodeQuote) {
            sendInsertMessage("quote");
        }
        //删除线
        if (v == b.tvBbsCodeDeleteLine) {
            sendInsertMessage("del");
        }
        //加粗
        if (v == b.tvBbsCodeBold) {
            sendInsertMessage("b");
        }
        //下划线
        if (v == b.tvBbsCodeUnderLined) {
            sendInsertMessage("u");
        }
        //斜体
        if (v == b.tvBbsCodeItalic) {
            sendInsertMessage("i");

        }
        //段落标题
        if (v == b.tvBbsCodeHeader) {
            sendInsertMessage("h");
        }
        //列表
        if (v == b.tvBbsCodeList) {
            StringBuilder sb = new StringBuilder();
            sb.append("[list]").append("\n");
            for (int i = 0; i < 3; i++) {
                sb.append("[*]列表项").append(i + 1).append("\n");
            }
            sb.append("[/list]");
            sendInsertMessage(sb.toString(), null);
        }
    }

    /**
     * 暴露给js调用 选择颜色的方法
     *
     * @param name 颜色名称
     */
    @JavascriptInterface
    public void chooseColor(String name) {
        Log.i(TAG, "选择颜色: " + name);
        String start = String.format("[color=%s]", name);
        sendInsertMessage(start, "[/color]");
        // 关闭弹窗
        colorSelector.dismiss();
        colorSelector = null;
    }

    /**
     * 发送插入消息
     */
    private void sendInsertMessage(String start, String end) {
        getParentHandler().sendMessage(getParentHandler().obtainMessage(HandlerMessage.INSERT_TEXT, new InsertText(start, end)));
    }

    /**
     * 快捷插入无参数的bbsCode
     *
     * @param code bbsCode名称
     */
    private void sendInsertMessage(String code) {
        String start = String.format("[%s]", code);
        String end = String.format("[/%s]", code);
        sendInsertMessage(start, end);
    }
}